// 
//  Copyright 2011  comphilip
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
using System;
using System.IO;

namespace Dict4Engkoo.Result {
	/// <summary>
	/// Represent dict text response
	/// </summary>
	internal class TextResponse : IResult {
		/// <summary>Initializes a new instance of the <see cref="T:TextResponse"/> class</summary>
		/// <param name="Content"> Text content</param>
		/// <remarks>Empty mime content type, DICT client take it as text/plain</remarks>
		public TextResponse (string Content) : this(Content, string.Empty) {
		}

		/// <summary>Initializes a new instance of the <see cref="T:TextResponse"/> class</summary>
		/// <param name="Content"> Text content</param>
		/// <param name="ContentType">Mime content type</param>
		public TextResponse (string Content, string ContentType) {
			Utility.ArgumentValidator.ValidateEmptySpaceStringArgument (Content, "Content");
			Utility.ArgumentValidator.ValidateNullArgument (ContentType, "ContentType");
			
			this.Content = Content;
			this.ContentType = ContentType;
		}

		/// <summary>
		/// Gets text content
		/// </summary>
		public string Content { get; private set; }

		/// <summary>
		/// Gets mime content type
		/// </summary>
		public string ContentType { get; private set; }

		/// <summary>
		/// Render text context to DictContext's OutputWriter.
		/// </summary>
		/// <param name="Context">A <see cref="DictContext"/> contains OutputWriter.</param>
		public void Render (DictContext Context) {
			// render mime head if option mime is on
			if (Context.OptionMime) {
				if (!string.IsNullOrEmpty (ContentType)) {
					Context.OutputWriter.WriteLine ("Content-Type: ", ContentType);
					Context.OutputWriter.WriteLine ("Content-transfer-encoding: 8bit");
					// hard code for transfer encoding
				} else {
					Context.OutputWriter.WriteLine ();
					// default header, a blank line	
				}
			}
			
			using (StringReader reader = new StringReader (Content)) {
				string line;
				while (null != (line = reader.ReadLine ())) {
					// TODO : length overflow detection
					if (line.StartsWith (".", StringComparison.OrdinalIgnoreCase))
						Context.OutputWriter.WriteLine (".{0}", line);
					else
						//special for dot
						Context.OutputWriter.WriteLine (line);
				}
			}
			
			Context.OutputWriter.WriteLine (".");
			// end of text response.
		}
	}
}

